package io.gitee.mingbaobaba.security.starter.interceptor;

import io.gitee.mingbaobaba.security.core.exception.SecurityBaseException;
import io.gitee.mingbaobaba.security.core.factory.SecurityFactory;
import io.gitee.mingbaobaba.security.core.response.SecurityResponseWrapper;
import io.gitee.mingbaobaba.security.core.function.RouterFunction;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import java.lang.reflect.Method;
import java.util.Objects;

/**
 * <p>拦截器</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/8/29 16:49
 */
@Slf4j
public class SecurityInterceptor implements HandlerInterceptor {

    private RouterFunction<Method> router = m -> true;

    public SecurityInterceptor(RouterFunction<Method> router) {
        this.router = router;
    }

    public SecurityInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (handler instanceof HandlerMethod) {
                Method method = ((HandlerMethod) handler).getMethod();
                if ("error".equals(method.getName())) {
                    return false;
                }
                //执行自定义路由
                return router.run(method);
            }
        } catch (SecurityBaseException e) {
            SecurityResponseWrapper securityResponseWrapper = SecurityFactory.getSecurityResponseWrapper.get();
            Object result = securityResponseWrapper.wrapper(null, true, e);
            if (Objects.nonNull(result)) {
                response.setContentType(securityResponseWrapper.contentType());
                response.getWriter().print(result);
            } else {
                throw e;
            }
            return false;
        }
        return true;
    }

}
